package com.xuyang.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
 * 
 * @author 徐洋
 *  先在外部数据库执行下局sql命令，创建一个符合条件的数据库（注：数据库第一个列名最好是_id）
 *  CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')  
  	INSERT INTO "android_metadata" VALUES ('en_US')  
 * 功能：通过继承helper类来实现将apk自带的数据库文件导入本地，实现原始数据携带
 */
public class DataBaseHelper extends SQLiteOpenHelper {
	 private static String DB_PATH = "/data/data/com.example.bookmanager/databases/";  
	 private static String DB_NAME = "library";  
	 private SQLiteDatabase myDataBase;   
	 private final Context myContext;  
	 public DataBaseHelper(Context context) {
		 	super(context, DB_NAME, null, 1);  
	        this.myContext = context;  
	 }
	 //创建数据库,如果数据库已存在则不做任何操作
	 public void createDataBase(){  
	        boolean dbExist = checkDataBase();  
	        if(dbExist){  
	        }else{  
	            this.getReadableDatabase();  
	            try {  
	                copyDataBase();  
	            } catch (IOException e) {  
	                throw new Error("Error copying database");  
	            }  
	        }  
	    }  
	 //检查数据库，查看数据库是否已经存在，如果存在则返回true
	    private boolean checkDataBase(){  
	        SQLiteDatabase checkDB = null;  
	        try{  
	            String myPath = DB_PATH + DB_NAME;  
	            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);  
	        }catch(SQLiteException e){  
	        }  
	        if(checkDB != null){  
	            checkDB.close();  
	        }  
	        return checkDB != null ? true : false;  
	    }  
	    //拷贝文件存入本地
	    private void copyDataBase() throws IOException{  
	        InputStream myInput = myContext.getAssets().open(DB_NAME);  
	        String outFileName = DB_PATH + DB_NAME;  
	        OutputStream myOutput = new FileOutputStream(outFileName);  
	        byte[] buffer = new byte[1024];  
	        int length;  
	        while (-1!=(length = myInput.read(buffer))){  
	            myOutput.write(buffer, 0, length);  
	        }  
	        myOutput.flush();  
	        myOutput.close();  
	        myInput.close();  
	    }  
	   //打开数据库
	    public void openDataBase() throws SQLException{  
	        String myPath = DB_PATH + DB_NAME;  
	        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);  
	    }  
	    
	    //关闭数据库
	    @Override  
	    public synchronized void close() {  
	            if(myDataBase != null)  
	                myDataBase.close();  
	            super.close();  
	    }  
	    
	    @Override  
	    public void onCreate(SQLiteDatabase db) {  
	    }  
	    @Override  
	    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
	    }  
	    //查询数据
	    public ArrayList<String> getData(){
	    	ArrayList<String> list=new ArrayList<String>();
	    	if (myDataBase!=null) {
				Cursor cursor=myDataBase.query("stu_table", new String[]{"name"}, null, null, null, null, null);
				if (cursor!=null) {
					while(cursor.moveToNext()){
						list.add(cursor.getString(0));
					}
				}
			}else {
				Log.e("DataBaseHelper-getData", "未获取数据库");
			}
	    	return list;
	    }
}  